package com.opesoft.pf.hibernate;

import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.opesoft.pf.hibernate.HibernateSession;

public class SessionManager
{
	public Logger log=Logger.getLogger(SessionManager.class);

	SessionFactory sessionFactory;
	String configFile="/hibernate.cfg.xml";

	Map<Thread, HibernateSession> activeSessions=new HashMap<Thread, HibernateSession>();

	public void SessionManger(String configFile)
	{
		this.configFile=configFile;
	}

	public void init()
	{
		sessionFactory=new AnnotationConfiguration().configure(this.configFile).buildSessionFactory();
	}

	/**
	 * 创建一个当前线程的HibernateSession
	 */
	private void create()
	{
		Thread thread=Thread.currentThread();

		if(activeSessions.get(thread)==null)
		{
			if(sessionFactory==null||sessionFactory.isClosed()) init();

			Session se=sessionFactory.openSession();
			if(se==null) se=sessionFactory.getCurrentSession();

			HibernateSession hs=new HibernateSession(se);
			activeSessions.put(thread,hs);

			log.debug("Create new session.");
		}
	}

	public Session open()
	{
		Thread thread=Thread.currentThread();

		HibernateSession hs=activeSessions.get(thread);
		if(hs==null)
		{
			create();
			hs=activeSessions.get(thread);
		}

		hs.beginTransaction();
		return hs.getSession();
	}

	/**
	 * 结束Session的Transaction
	 * 
	 * @param submit
	 *            是否提交，为False的时候回滚
	 */
	public void commit(boolean submit)
	{
		Thread thread=Thread.currentThread();
		HibernateSession hs=activeSessions.get(thread);

		hs.commitTransaction(submit);
	}

	/**
	 * 提交Session的Transaction
	 */
	public void commit()
	{
		Thread thread=Thread.currentThread();
		HibernateSession hs=activeSessions.get(thread);

		hs.commitTransaction(true);
	}

	/**
	 * 回滚Session的Transaction
	 */
	public void rollback()
	{
		Thread thread=Thread.currentThread();
		HibernateSession hs=activeSessions.get(thread);

		hs.commitTransaction(false);
	}

	public void close()
	{
		Thread thread=Thread.currentThread();
		HibernateSession hs=activeSessions.get(thread);
		if(hs!=null)
		{
			Session se=hs.getSession();
			if(se.isOpen()) se.close();

			activeSessions.remove(thread);

			log.debug("Close the session.");
		}
	}

	public int getActiveSessionCount()
	{
		return activeSessions.size();
	}

}
